package com.example.electronicmall.application;

import android.content.Context;

import com.example.electronicmall.bean.MineOrder;
import com.example.electronicmall.bean.MineOrderData;
import com.example.electronicmall.bean.MineOrderObject;
import com.example.electronicmall.http.IMineOrderPresenter;

import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


public class MineOrderPresenter implements IMineOrderPresenter {

    Context context;

    public MineOrderPresenter(Context context) {
        this.context = context;
    }

    @Override
    public void requestOrder(int memberId, OnMineOrderListener listener) {
        BaseApplication.mineOrderRequest
                .requestOrder(memberId)
                //通过调度器（schedulers）指定在某个线程中执行
                .subscribeOn(Schedulers.io())
                .map(new Func1<MineOrderObject<MineOrderData>, MineOrderData>() {
                    @Override
                    public MineOrderData call(MineOrderObject<MineOrderData> mineOrderDataMineOrderObject) {
                        return mineOrderDataMineOrderObject.getData();
                    }
                })
                .flatMap(new Func1<MineOrderData, Observable<MineOrder>>() {
                    @Override
                    public Observable<MineOrder> call(MineOrderData mineOrderData) {
                        return Observable.from(mineOrderData.getList());
                    }
                })
                //通过调度器（schedulers）切换线程
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<MineOrder>() {
                    @Override
                    public void onCompleted() {
                    }
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(MineOrder mineOrder) {
                        listener.onMineOrder(mineOrder);
                    }
                });
    }

    public interface OnMineOrderListener {
        void onMineOrder(MineOrder mineOrder);
    }

}
